import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class SQLConnection {
    private String name;
    private String url;
    private String user;
    private String password;
    private String nameDriver;
    private Connection conn;
    Statement stmt;
    ResultSet rs;

    public SQLConnection(Map<String, Object> map) throws ClassNotFoundException, SQLException {
        name=(String)map.get(Constant.DataBaseConstant.CONNECTION_NAME);
        url = (String) map.get(Constant.DataBaseConstant.URL);
        user = (String) map.get(Constant.DataBaseConstant.USER_NAME);
        password = (String) map.get(Constant.DataBaseConstant.PASSWORD);
        nameDriver = (String) map.get(Constant.DataBaseConstant.DRIVER_NAME);
        Class.forName(nameDriver);
        conn = DriverManager.getConnection(url, user, password);
        stmt=conn.createStatement();
    }
    //通过sql获取数据集合
    List<Map<String, Object>> getResultMap(String sql) throws SQLException {
        rs = stmt.executeQuery(sql);
        List<Map<String, Object>> dataList = new ArrayList<>();
        while (rs.next()) {
            ResultSetMetaData rsMeta = rs.getMetaData();
            int columnCount = rsMeta.getColumnCount();
            Map<String, Object> dataMap = new HashMap<>();
            for (int i = 1; i <= columnCount; i++) {
                dataMap.put(rsMeta.getColumnLabel(i), rs.getObject(i));
            }
            dataList.add(dataMap);
        }
        return dataList;
    }

    //释放数据库连接
    public void close() {
        try {
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    public String getName(){
        return this.name;
    }


}




